<!DOCTYPE html>
<html>

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
    <meta http-equiv="Expires" content="0" />
</head>

<body style="width: 100%; height: 100%; overflow: hidden; margin: 0; background-color: #38353D; color: #ffffff;">
    <div style="padding: 15px;">
        <div style="display: flex; align-items: center; height: 40px; background-color: #45424A;">
            <div style="padding: 0 15px;">分屏</div>
            <div style="cursor: pointer; margin-right: 20px;" onclick="changeWndNum('2')">
                <img src="./ico_21.png" alt="" srcset="">
            </div>
            <div style="cursor: pointer;" onclick="changeWndNum('3')">
                <img src="./ico_23.png" alt="" srcset="">
            </div>
        </div>

        <div id="divPlugin" class="plugin" style="width: 100%; height: calc(100vh - 80px); margin-top: 8px;"></div>
    </div>
</body>
<script src="./jquery-1.7.1.min.js"></script>
<script id="videonode" src="./webVideoCtrl.js"></script>
<script>
    // 初始化插件

    // 全局保存当前选中窗口
    var g_iWndIndex = 0; //可以不用设置这个变量，有窗口参数的接口中，不用传值，开发包会默认使用当前选择窗口
    var g_oLocalConfig = null; //本地配置

    //错误码
    //通用错误
    var ERROR_CODE_UNKNOWN = 1000; //未知错误
    var ERROR_CODE_NETWORKERROR = 1001; //网络错误
    var ERROR_CODE_PARAMERROR = 1002; //缺少插件元素

    //登录模块
    var ERROR_CODE_LOGIN_NOLOGIN = 2000; // 未登录
    var ERROR_CODE_LOGIN_REPEATLOGIN = 2001; //设备已登录，重复登录
    var ERROR_CODE_LOGIN_NOSUPPORT = 2002; //当前设备不支持Digest登录

    //预览播放
    var ERROR_CODE_PLAY_PLUGININITFAIL = 3000; //插件初始化失败
    var ERROR_CODE_PLAY_NOREPEATPLAY = 3001; //当前窗口已经在预览
    var ERROR_CODE_PLAY_PLAYBACKABNORMAL = 3002; //回放异常
    var ERROR_CODE_PLAY_PLAYBACKSTOP = 3003; //回放停止
    var ERROR_CODE_PLAY_NOFREESPACE = 3004; //录像过程中，硬盘容量不足

    //对讲
    var ERROR_CODE_TALK_FAIL = 5000; //语音对讲失败

    var version = 'V3.3.0build20230322';
    var videoPort = ["8055", "8056", "8057", "8058"];
    var videoPort2 = ['8075', '8076', '8077', '8078'];
    var rtspPort = ['5541', '5542', '5543', '5544'];
    var params = {}
    $(function () {
        if (window.location.search) {
            var parts = window.location.search.substring(1).split('&');
            for (var i = 0; i < parts.length; i++) {
                var nv = parts[i].split('=');
                if (!nv[0]) continue;
                params[nv[0]] = nv[1] || true;
            }
        }
        var currentId = params.id;
        var rc = params.rc;
        if (rc == "false") {
            // $(".ptz").hide();
            // $("#divPlugin").attr("style", "position: relative; width: 1150px; height: 780px; left: 450px; top: 110px");
        }
        setTimeout(() => {
            resize();
            // 初始化插件参数及插入插件
            WebVideoCtrl.I_InitPlugin({
                bWndFull: false, //是否支持单窗口双击全屏，默认支持 true:支持 false:不支持
                iWndowType: 2,
                cbSelWnd: function (xmlDoc) {
                    g_iWndIndex = parseInt($(xmlDoc).find('SelectWnd').eq(0).text(), 10);
                    clickWnd(g_iWndIndex, 1);
                    var szInfo = '当前选择的窗口编号：' + g_iWndIndex;
                    showCBInfo(szInfo);
                },
                cbDoubleClickWnd: function (iWndIndex, bFullScreen) {
                    console.log("窗口双击", iWndIndex, bFullScreen);
                    clickWnd(iWndIndex, 2);
                    var szInfo = '当前放大的窗口编号：' + iWndIndex;
                    if (!bFullScreen) {
                        szInfo = '当前还原的窗口编号：' + iWndIndex;
                    }
                    showCBInfo(szInfo);
                },
                cbEvent: function (iEventType, iParam1, iParam2) {
                    if (2 == iEventType) {
                        // 回放正常结束
                        showCBInfo('窗口' + iParam1 + '回放结束！');
                    } else if (-1 == iEventType) {
                        showCBInfo('设备' + iParam1 + '网络错误！');
                    } else if (3001 == iEventType) {
                        clickStopRecord(g_szRecordType, iParam1);
                    }
                },
                cbInitPluginComplete: function () {
                    WebVideoCtrl.I_InsertOBJECTPlugin('divPlugin').then(
                        () => {
                            console.log(currentId);
                            if (params.login != "false") {
                                clickStartRealPlay();
                            }
                            WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
                                if (bFlag) {
                                    alert('检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！');
                                }
                            });
                        },
                        () => {
                            alert('插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！');
                        }
                    );
                }
            });
        }, 1000);
    });
    $(window).on('resize', resize);
    // 在iframe中执行的脚本
    function resize() {
        if (!window.frameElement) {
            return;
        }
        // 解决iframe中嵌入海康插件初始化问题:
        // 1. 获取iframe相比于窗口的偏移量;
        var offset = window.parent.document.elementFromPoint(
            window.frameElement.getBoundingClientRect().left,
            window.frameElement.getBoundingClientRect().top
        ).getBoundingClientRect();
        // console.log('父级元素的偏移量:', offset);
        if (offset && (offset.top || offset.left)) {
            $("#divPlugin").css("margin-top", Number(offset.top) + 8 + "px");
            $("#divPlugin").css("margin-left", Number(offset.left) + "px");
        }
    }

    // 开始预览-改写
    function clickStartRealPlay() {
        console.log("开始登录");
        var ipselectData = params.id || "";
        var ipdata = ipselectData.split('_');
        var szIP = ipdata[0];
        var ipAndPort = szIP.split(':');
        var rtspPort = ipdata[1];
        var currentIp = ipAndPort[0];
        var currentPort = ipAndPort[1];
        var szPort = currentPort,
            szUsername = 'admin',
            szPassword = '123456789a';
        var list = params.coal == "2" ? videoPort2 : videoPort;
        list.forEach((itemPort, index) => {
            var szDeviceIdentify = currentIp + '_' + itemPort;
            WebVideoCtrl.I_Login(currentIp, 1, itemPort, szUsername, szPassword, {
                timeout: 3000,
                success: function (xmlDoc) {
                    showOPInfo(szDeviceIdentify + " 登录成功！");
                    show2(2, szDeviceIdentify, rtspPort[index], index);
                },
                error: function (oError) {
                    if (ERROR_CODE_LOGIN_REPEATLOGIN === status) {
                        showOPInfo(szDeviceIdentify + " 已登录过！");
                        show2(2, szDeviceIdentify, rtspPort);
                    } else {
                        showOPInfo(szDeviceIdentify + " 登录失败！", oError.errorCode, oError.errorMsg);
                    }
                }
            });
        });
    }

    /** 预览 */
    function show2(iChannelID, szDeviceIdentify, rtspPort, iWndIndex) {
        var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
            iRtspPort = rtspPort,
            iChannelID = parseInt(iChannelID, 10),
            bZeroChannel = false,
            szInfo = '';
        var startRealPlay = function () {
            WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
                iWndIndex: iWndIndex,
                iStreamType: 1,
                iChannelID: iChannelID,
                bZeroChannel: bZeroChannel,
                success: function () {
                    szInfo = '开始预览成功！'
                    showOPInfo(szDeviceIdentify + " " + szInfo);
                },
                error: function (oError) {
                    showOPInfo(szDeviceIdentify + " 开始预览失败！", oError.errorCode, oError.errorMsg);
                }
            });
        }

        if (oWndInfo != null) {
            // 已经在播放了，先停止
            WebVideoCtrl.I_Stop({
                success: function () {
                    startRealPlay();
                }
            });
        } else {
            startRealPlay();
        }
    }

    // 窗口点击,type:1单击，type：2双击
    function clickWnd(index, type) {
        console.log(`窗口点击:${type == 2 ? "双击" : "单击"}`, index);
        // 向父页面发送消息
        var setMsg = {
            videoPort: params.coal == 2 ? videoPort2[index] : videoPort[index],
            rtspPort: rtspPort[index],
            coal: params.coal
        }
        window.parent.postMessage(setMsg, window.location.origin);
    }
    // PTZ控制 9为自动，1,2,3,4,5,6,7,8为方向PTZ
    var g_bPTZAuto = false;

    function showOPInfo(szInfo, status, xmlDoc) {
        var szTip = "<div>" + szInfo;
        if (typeof status != "undefined" && status != 200) {
            var szStatusString = $(xmlDoc).find("statusString").eq(0).text();
            var szSubStatusCode = $(xmlDoc).find("subStatusCode").eq(0).text();
            if ("" === szSubStatusCode) {
                if ("" === szSubStatusCode && "" === szStatusString) {
                    szTip += "(" + status + ")";
                }
                else {
                    szTip += "(" + status + ", " + szStatusString + ")";
                }
            } else {
                szTip += "(" + status + ", " + szSubStatusCode + ")";
            }
        }
        szTip += "</div>";

        console.log(szTip);
    }

    // 显示操作信息

    // 设置本地参数
    // 源代码开始


    // 显示回调信息
    function showCBInfo(szInfo) {
        szInfo = "<div>" + szInfo + "</div>";
        console.log(szInfo);
    }

    // 获取窗口尺寸
    function getWindowSize() {
        var nWidth = $(this).width() + $(this).scrollLeft(),
            nHeight = $(this).height() + $(this).scrollTop();

        return { width: nWidth, height: nHeight };
    }

    // 窗口分割数
    function changeWndNum(iType) {
        iType = parseInt(iType, 10);
        WebVideoCtrl.I_ChangeWndNum(iType).then(() => {
            showOPInfo("窗口分割成功！");
        }, (oError) => {
            var szInfo = "窗口分割失败！";
            showOPInfo(szInfo, oError.errorCode, oError.errorMsg);
        });
    }

    // 退出
    function clickLogout() {
        var szDeviceIdentify = "";
        if (null == szDeviceIdentify) {
            return;
        }

        WebVideoCtrl.I_Logout(szDeviceIdentify).then(() => {
            showOPInfo(szDeviceIdentify + " " + "退出成功！");
        }, () => {
            showOPInfo(szDeviceIdentify + " " + "退出失败！");
        });
    }

    // 停止预览
    function clickStopRealPlay() {
        var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
            szInfo = "";

        if (oWndInfo != null) {
            WebVideoCtrl.I_Stop({
                success: function () {
                    szInfo = "停止预览成功！";
                    showOPInfo(oWndInfo.szDeviceIdentify + " " + szInfo);
                },
                error: function (oError) {
                    showOPInfo(szDeviceIdentify + " 停止预览失败！", oError.errorCode, oError.errorMsg);
                }
            });
        }
    }

    // 开始录像
    var g_szRecordType = "";

    // 停止录像
    function clickStopRecord(szType, iWndIndex) {
        if ("undefined" === typeof iWndIndex) {
            iWndIndex = g_iWndIndex;
        }
        var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex),
            szInfo = "";

        if (oWndInfo != null) {
            WebVideoCtrl.I_StopRecord({
                success: function () {
                    if ('realplay' === szType) {
                        szInfo = "停止录像成功！";
                    } else if ('playback' === szType) {
                        szInfo = "停止剪辑成功！";
                    }
                    showOPInfo(oWndInfo.szDeviceIdentify + " " + szInfo);
                },
                error: function (oError) {
                    if ('realplay' === szType) {
                        szInfo = "停止录像失败！";
                    } else if ('playback' === szType) {
                        szInfo = "停止剪辑失败！";
                    }
                    sshowOPInfo(szDeviceIdentify + szInfo, oError.errorCode, oError.errorMsg);
                }
            });
        }
    }


    // 搜索录像
    var g_iSearchTimes = 0;

    // 下载录像
    var g_iDownloadID = -1;
    var g_tDownloadProcess = 0;

    // 重连
    function reconnect(szDeviceIdentify) {
        WebVideoCtrl.I_Reconnect(szDeviceIdentify, {
            timeout: 3000,
            success: function (xmlDoc) {
                // $("#restartDiv").remove();
            },
            error: function () {
                setTimeout(function () { reconnect(szDeviceIdentify); }, 5000);
            }
        });
    }

    function loadXML(szXml) {
        if (null == szXml || "" == szXml) {
            return null;
        }

        var oXmlDoc = null;

        if (window.DOMParser) {
            var oParser = new DOMParser();
            oXmlDoc = oParser.parseFromString(szXml, "text/xml");
        } else {
            oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            oXmlDoc.async = false;
            oXmlDoc.loadXML(szXml);
        }

        return oXmlDoc;
    }

    function toXMLStr(oXmlDoc) {
        var szXmlDoc = "";

        try {
            var oSerializer = new XMLSerializer();
            szXmlDoc = oSerializer.serializeToString(oXmlDoc);
        } catch (e) {
            try {
                szXmlDoc = oXmlDoc.xml;
            } catch (e) {
                return "";
            }
        }
        if (szXmlDoc.indexOf("<?xml") == -1) {
            szXmlDoc = "<?xml version='1.0' encoding='utf-8'?>" + szXmlDoc;
        }

        return szXmlDoc;
    }

    function encodeString(str) {
        if (str) {
            return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        } else {
            return "";
        }
    }
    // 源代码结束
</script>
</html>
<style></style>